package com.djinquan.common.util;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @Desc:redis工具类
 * @Group:美的集团-营销系统-技术组
 * @Author dengjq15
 * @Date 2022/7/18
 */
@Component
public class RedisUtil {

    protected Logger logger = LoggerFactory.getLogger(RedisUtil.class);

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 设置对象
     * @param key
     * @param object
     * @param min
     */
    public void setObject(String key,Object object,Long min){
        String str = JSON.toJSONString(object);
        if(min==null||min<=0) {
            redisTemplate.opsForValue().set(key, str);
        }
        else{
            redisTemplate.opsForValue().set(key,str,min, TimeUnit.MINUTES);
        }
    }

    /**
     * 获取对象
     * @param key
     * @return
     */
    public Object getObject(String key){
        return redisTemplate.opsForValue().get(key);
    }

    /**
     * 删除对象
     * @param key
     */
    public void delKey(String key){
        redisTemplate.delete(key);
    }

    /**
     * 对某对象设置失效时间(多少分钟后失效)
     * @param key
     * @param min
     */
    public void setExprice(String key,Long min){
        if(!FunUtil.objIsNull(min)&&min>0) {
            redisTemplate.expire(key,min,TimeUnit.MINUTES);
        }
    }
}
